package models

import (
	"fmt"
	"gorm.io/gorm"
	"time"
)

type Orders struct {
	gorm.Model
	UserId      int64
	OrderSn     string
	GoodsId     int64
	Num         int64
	Total       float32
	RiderId     int64 //骑手ID
	OrderStatus int64 `gorm:"type:int;default:1;comment:0为商家已接单 默认1为配送中 2为已完成"`
}

func (o *Orders) Create() error {
	return DB.Create(&o).Error
}

func (o *Orders) GetOrderById() error {
	return DB.Where("id = ?", o.ID).Limit(1).Find(&o).Error
}

func (o *Orders) StatusUpdate(ordersId, status int) error {
	return DB.Model(&o).Where("id=?", ordersId).Update("status", status).Error
}

type OrdersTotal struct {
	Counts    int64
	Amounts   float32
	OrderData string
}

func To(db *gorm.DB) {
	// 计算统计时间范围（过去一年）
	n := time.Now()
	t := n.Add(-time.Hour * 24 * 30)

	var orderTotal []OrdersTotal

	// 使用GORM执行SQL查询
	db.Model(&Orders{}).
		Select("COUNT(orders.id) as counts,SUM(total) as amounts,DATE_FORMAT(created_at,'%Y-%m-%d') as order_date").
		Where("created_at>?", t).
		Group("order_date").
		Find(&orderTotal)

}

type UserConsumption struct {
	UserID      uint64  `json:"user_id"`
	Month       string  `json:"month"`
	TotalAmount float64 `json:"total_amount"`
	OrderCount  int     `json:"order_count"`
}

func GetUserConsumptionData(db *gorm.DB) {
	// 计算统计时间范围（过去一年）
	endDate := time.Now()
	startDate := endDate.AddDate(-1, 0, 0)

	var results []UserConsumption

	// 使用GORM执行SQL查询
	db.Model(&Orders{}).
		Select("user_id, DATE_FORMAT(order_time, '%Y-%m') as month, SUM(order_amount) as total_amount, COUNT(id) as order_count").
		Where("order_time BETWEEN ? AND ?", startDate, endDate).
		Group("user_id, month").
		Order("user_id, month").
		Find(&results)

}

type MerchantTimeSlotSales struct {
	MerchantID uint64  `json:"merchant_id"`
	Date       string  `json:"date"`
	TimeSlot   string  `json:"time_slot"`
	TotalSales float64 `json:"total_sales"`
	OrderCount int     `json:"order_count"`
}

// 获取所有商家每天各时段的营业额
func GetAllMerchantsTimeSlotSales(db *gorm.DB, startDate, endDate time.Time) ([]MerchantTimeSlotSales, error) {
	var results []MerchantTimeSlotSales

	err := db.Model(&Orders{}).
		Select("merchant_id, DATE(order_time) as date, "+
			"CASE "+
			"   WHEN HOUR(order_time) BETWEEN 6 AND 10 THEN '早餐' "+
			"   WHEN HOUR(order_time) BETWEEN 11 AND 14 THEN '午餐' "+
			"   WHEN HOUR(order_time) BETWEEN 17 AND 21 THEN '晚餐' "+
			"   ELSE '其他' "+
			"END as time_slot, "+
			"SUM(order_amount) as total_sales, COUNT(id) as order_count").
		Where("order_time BETWEEN ? AND ?", startDate, endDate).
		Group("merchant_id, DATE(order_time), time_slot").
		Order("merchant_id, date, FIELD(time_slot, '早餐', '午餐', '晚餐', '其他')").
		Find(&results).Error

	if err != nil {
		return nil, fmt.Errorf("查询商家时段营业额失败: %v", err)
	}

	return results, nil
}
